package com.itmuch.cloud.controller;

import com.itmuch.cloud.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class MovieController {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private DiscoveryClient discoveryClient;

    @LoadBalanced
    @GetMapping("/user/{id}")
    public User findById(@PathVariable Long id) {
        return restTemplate.getForObject("http://localhost:8000/user/" + id, User.class);
    }

    @GetMapping("/user-instance")
    public List<Map<String, Object>> showInfo() {
        // 获取服务实例列表
        List<ServiceInstance> instances = discoveryClient.getInstances("microservice-provider-user-metadata");

        // 构建包含元数据的返回结果
        return instances.stream().map(instance -> {
            Map<String, Object> result = new HashMap<>();
            result.put("host", instance.getHost());
            result.put("port", instance.getPort());
            result.put("serviceId", instance.getServiceId());
            result.put("metadata", instance.getMetadata());  // 获取所有元数据
            result.put("my-metadata", instance.getMetadata().get("my-metadata"));  // 获取自定义元数据
            return result;
        }).toList();
    }
}
